package com.supersit.greensproject.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;

import com.andview.refreshview.XRefreshView;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.activity.BaseFragment;
import com.supersit.greensproject.activity.PriceGatherEditActivity;
import com.supersit.greensproject.adapter.PriceGatherAdapter;
import com.supersit.greensproject.entity.PriceGather;
import com.supersit.greensproject.utils.KeyBoardUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.CustomDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

/**
 * 数据查询
 * Created by cong on 2016/7/14.
 */
@ContentView(R.layout.fragment_price_gather_selected_data)
public class PriceGatherSelectedDataFragment extends BaseFragment {
    @ViewInject(R.id.lv_selected_data)
    private ListView lvDataList;
    @ViewInject(R.id.et_search_key_word)
    private EditText etSearchKeyWord;
    @ViewInject(R.id.sp_select_maket_type)
    private Spinner spMaketType;
    private Context context;
    private PriceGatherAdapter priceGatherAdapter;
    private List<PriceGather> list;
    @ViewInject(R.id.custom_view)
    private XRefreshView refreshView;
    @ViewInject(R.id.ib_search_icon_bt)
    private ImageButton ibSearch;
    public static long lastRefreshTime;
    //每页查询的数量
    private final int selectCount = 20;
    //每页查询的开始条数
    private int selectStartNum = 0;
    private DbManager db;
    private int maketType;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = getActivity();
        initVariable();
        bindListener();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void initVariable() {
        KeyBoardUtils.closeKeybord(etSearchKeyWord, getActivity());
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                context, R.array.all_maket_type, R.layout.spinner_text);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMaketType.setAdapter(adapter);
        db = XUtilsDbManager.getInstance();
        try {
            list = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
            priceGatherAdapter = new PriceGatherAdapter(context, list);
            lvDataList.setAdapter(priceGatherAdapter);
        } catch (DbException e) {
            e.printStackTrace();
        }
        setRefreshViewOperate(true);

    }

    private void bindListener() {
        // spArea.setOnItemSelectedListener(onItemSelectedListener);
        spMaketType.setOnItemSelectedListener(onItemSelectedListener);
        lvDataList.setOnItemClickListener(onItemClickListener);
        refreshView.setXRefreshViewListener(simpleXRefreshListener);
        ibSearch.setOnClickListener(onClickListener);
        lvDataList.setOnItemLongClickListener(onItemLongClickListener);

    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(), PriceGatherEditActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("pricegather", list.get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };
    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (null != list && list.size() > 0)
                list.clear();
            selectStartNum = 0;
            setRefreshViewOperate(true);
            if (0 == position) {
                maketType = position;
                try {
                    list = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != list && list.size() > 0)
                        priceGatherAdapter.setData(list);
                    priceGatherAdapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                maketType = position - 1;
                try {
                    list = db.selector(PriceGather.class).where("isDelete", "=", 1).and("maketType", "=", maketType).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != list && list.size() > 0)
                        priceGatherAdapter.setData(list);
                    priceGatherAdapter.notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    private void setRefreshViewOperate(boolean flag) {

        if (flag) {
            // 设置是否可以下拉刷新
            if (!refreshView.getPullRefreshEnable()) {
                refreshView.setPullRefreshEnable(true);
            }
            // 设置是否可以上拉加载
            if (!refreshView.getPullLoadEnable()) {
                refreshView.setPullLoadEnable(true);
            }
        } else {
            if (refreshView.getPullRefreshEnable()) {
                refreshView.setPullRefreshEnable(false);
            }
            if (refreshView.getPullLoadEnable()) {
                refreshView.setPullLoadEnable(false);
            }
        }
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);
        // 设置时候可以自动刷新
        refreshView.setAutoRefresh(false);
    }

    private XRefreshView.SimpleXRefreshListener simpleXRefreshListener = new XRefreshView.SimpleXRefreshListener() {
        @Override
        public void onRefresh() {
            super.onRefresh();
            if (null != list && list.size() > 0)
                list.clear();
            selectStartNum = 0;
            if (0 == maketType) {
                try {
                    list = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != list && list.size() > 0) {
                        priceGatherAdapter.setData(list);
                        priceGatherAdapter.notifyDataSetChanged();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                selectStartNum = 0;
                try {
                    list = db.selector(PriceGather.class).where("isDelete", "=", 1).and("maketType", "=", maketType - 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != list && list.size() > 0) {
                        priceGatherAdapter.setData(list);
                        priceGatherAdapter.notifyDataSetChanged();
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            refreshView.stopRefresh();
        }

        @Override
        public void onLoadMore(boolean isSilence) {
            super.onLoadMore(isSilence);
            selectStartNum += 20;
            if (0 == maketType) {
                try {
                    List<PriceGather> newData = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != newData && newData.size() > 0) {
                        list.addAll(newData);
                        if (null != list && list.size() > 0)
                            priceGatherAdapter.setData(list);
                        priceGatherAdapter.notifyDataSetChanged();
                    } else {
                        T.showShort(context, R.string.next_is_null);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    List<PriceGather> newData = db.selector(PriceGather.class).where("isDelete", "=", 1).and("maketType", "=", maketType).limit(selectCount).offset(selectStartNum).findAll();
                    if (null != newData && newData.size() > 0) {
                        list.addAll(newData);
                        if (null != list && list.size() > 0)
                            priceGatherAdapter.setData(list);
                        priceGatherAdapter.notifyDataSetChanged();
                    } else {
                        T.showShort(context, R.string.next_is_null);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            refreshView.stopLoadMore();
        }
    };
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ib_search_icon_bt:
                    if (!TextUtils.isEmpty(etSearchKeyWord.getText().toString().trim())) {
                        String searchKey = etSearchKeyWord.getText().toString().trim();
                        if (null != list && list.size() > 0)
                            list.clear();
                        selectStartNum = 0;
                        setRefreshViewOperate(false);
                        try {
                            list = db.selector(PriceGather.class).where("isDelete", "=", 1).and("maketName", "like", "%" + searchKey + "%").limit(selectCount).offset(selectStartNum).findAll();
                            if (null != list && list.size() > 0) {
                                priceGatherAdapter.setData(list);
                                priceGatherAdapter.notifyDataSetChanged();
                            } else {
                                T.showShort(context, String.format(context.getResources().getString(R.string.serch_not_result_for_maket), searchKey));
                                priceGatherAdapter.setData(list);
                                priceGatherAdapter.notifyDataSetChanged();
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            selectStartNum = 0;
                            //setRefreshViewOperate(true);
                            list = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
                            if (null != list && list.size() > 0)
                                priceGatherAdapter.setData(list);
                            priceGatherAdapter.notifyDataSetChanged();
                            spMaketType.setSelection(0);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        spMaketType.setSelection(0);
        maketType = 0;
        selectStartNum = 0;
        setRefreshViewOperate(true);
        try {
            list = db.selector(PriceGather.class).where("isDelete", "=", 1).limit(selectCount).offset(selectStartNum).findAll();
            if (null != list && list.size() > 0)
                priceGatherAdapter.setData(list);
            priceGatherAdapter.notifyDataSetChanged();
            etSearchKeyWord.setText("");
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private AdapterView.OnItemLongClickListener onItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int postion, long l) {
            CustomDialog dialog;
            CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
            customBuilder.setTitle(R.string.delete);
            customBuilder.setMessage(R.string.custom_dialog_maket_title);
            customBuilder.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    PriceGather pg = list.get(postion);
                    pg.setOperationsTatus(0);
                    try {
                        db.update(pg, "operationsTatus");
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    T.showShort(context, R.string.synchorization_update_delete);
                    dialogInterface.dismiss();
                    onResume();
                }
            });
            customBuilder.setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            dialog = customBuilder.create();
            dialog.show();
            return true;
        }
    };
}
